// 初始化所有图表
let charts = {
    customerDistribution: null,
    customerBehavior: null,
    assetDistribution: null,
    marketingEffect: null,
    highValueCustomers: null
};

// 更新时间显示
function updateDateTime() {
    const now = new Date();
    document.getElementById('updateTime').textContent = now.toLocaleString();
}

// 初始化图表
function initCharts() {
    // 客户分布图表
    charts.customerDistribution = echarts.init(document.getElementById('customerDistribution'));
    // 客户行为雷达图
    charts.customerBehavior = echarts.init(document.getElementById('customerBehavior'));
    // 资产分布图表
    charts.assetDistribution = echarts.init(document.getElementById('assetDistribution'));
    // 营销效果图表
    charts.marketingEffect = echarts.init(document.getElementById('marketingEffect'));
    // 高价值客户矩阵图
    charts.highValueCustomers = echarts.init(document.getElementById('highValueCustomers'));
}

// 加载概览数据
function loadOverview() {
    $.get('/api/overview', function(data) {
        $('#totalCustomers .number').text(data.total_customers.toLocaleString());
        $('#totalAssets .number').text('¥' + (data.total_assets / 100000000).toFixed(2) + '亿');
        $('#activeUsers .number').text(data.active_users.toLocaleString());
    });
}

// 更新客户分布图表
function updateCustomerDistribution() {
    $.get('/api/customer_distribution', function(data) {
        const option = {
            title: {
                text: '客户基础分布',
                textStyle: {
                    color: '#fff'
                }
            },
            tooltip: {
                trigger: 'item'
            },
            legend: {
                top: '5%',
                left: 'center',
                textStyle: {
                    color: '#fff'
                }
            },
            series: [
                {
                    name: '年龄分布',
                    type: 'pie',
                    radius: ['40%', '70%'],
                    avoidLabelOverlap: false,
                    itemStyle: {
                        borderRadius: 10,
                        borderColor: '#fff',
                        borderWidth: 2
                    },
                    label: {
                        show: false,
                        position: 'center'
                    },
                    emphasis: {
                        label: {
                            show: true,
                            fontSize: '14',
                            fontWeight: 'bold'
                        }
                    },
                    labelLine: {
                        show: false
                    },
                    data: Object.entries(data.age_distribution).map(([name, value]) => ({
                        name,
                        value
                    }))
                }
            ]
        };
        charts.customerDistribution.setOption(option);
    });
}

// 更新客户行为雷达图
function updateCustomerBehavior() {
    $.get('/api/customer_behavior', function(data) {
        const option = {
            title: {
                text: '客户行为分析',
                textStyle: {
                    color: '#fff'
                }
            },
            radar: {
                indicator: [
                    { name: 'APP登录频次', max: 100 },
                    { name: '产品浏览时长', max: 100 },
                    { name: '产品持有数', max: 100 },
                    { name: '月均投资次数', max: 100 },
                    { name: '信用卡消费', max: 100 }
                ],
                axisLine: {
                    lineStyle: {
                        color: '#fff'
                    }
                },
                splitLine: {
                    lineStyle: {
                        color: 'rgba(255, 255, 255, 0.3)'
                    }
                }
            },
            series: [{
                name: '客户行为指标',
                type: 'radar',
                data: [{
                    value: [
                        data.app_login,
                        data.view_time,
                        data.product_count,
                        data.investment_count,
                        data.credit_expense
                    ],
                    name: '平均水平'
                }]
            }]
        };
        charts.customerBehavior.setOption(option);
    });
}

// 更新资产分布图表
function updateAssetDistribution() {
    $.get('/api/asset_distribution', function(data) {
        const option = {
            title: {
                text: '资产类型分布',
                textStyle: {
                    color: '#fff'
                }
            },
            tooltip: {
                trigger: 'axis',
                axisPointer: {
                    type: 'shadow'
                }
            },
            xAxis: {
                type: 'category',
                data: ['存款', '理财', '基金', '保险'],
                axisLabel: {
                    color: '#fff'
                }
            },
            yAxis: {
                type: 'value',
                axisLabel: {
                    color: '#fff',
                    formatter: function(value) {
                        return '¥' + (value / 10000).toFixed(0) + '万';
                    }
                }
            },
            series: [{
                data: [
                    data.deposit_balance,
                    data.financial_balance,
                    data.fund_balance,
                    data.insurance_balance
                ],
                type: 'bar',
                showBackground: true,
                backgroundStyle: {
                    color: 'rgba(180, 180, 180, 0.2)'
                }
            }]
        };
        charts.assetDistribution.setOption(option);
    });
}

// 更新营销效果图表
function updateMarketingEffect() {
    $.get('/api/marketing_effect', function(data) {
        const months = Object.keys(data).sort();
        const values = months.map(month => data[month] * 100);

        const option = {
            title: {
                text: '营销效果分析',
                textStyle: {
                    color: '#fff'
                }
            },
            tooltip: {
                trigger: 'axis'
            },
            xAxis: {
                type: 'category',
                data: months,
                axisLabel: {
                    color: '#fff'
                }
            },
            yAxis: {
                type: 'value',
                axisLabel: {
                    formatter: '{value}%',
                    color: '#fff'
                }
            },
            series: [{
                data: values,
                type: 'line',
                smooth: true
            }]
        };
        charts.marketingEffect.setOption(option);
    });
}

// 更新高价值客户矩阵图
function updateHighValueCustomers() {
    $.get('/api/high_value_customers', function(data) {
        const option = {
            title: {
                text: '高价值客户矩阵',
                textStyle: {
                    color: '#fff'
                }
            },
            xAxis: {
                name: '总资产',
                nameTextStyle: {
                    color: '#fff'
                },
                axisLabel: {
                    color: '#fff',
                    formatter: function(value) {
                        return '¥' + (value / 10000).toFixed(0) + '万';
                    }
                }
            },
            yAxis: {
                name: '活跃度',
                nameTextStyle: {
                    color: '#fff'
                },
                axisLabel: {
                    color: '#fff'
                }
            },
            series: [{
                type: 'scatter',
                data: data,
                symbolSize: function(data) {
                    return Math.sqrt(data[2]) * 5;
                }
            }]
        };
        charts.highValueCustomers.setOption(option);
    });
}

// 窗口大小改变时重置图表大小
function resizeCharts() {
    Object.values(charts).forEach(chart => {
        if (chart) {
            chart.resize();
        }
    });
}

// 初始化函数
function init() {
    updateDateTime();
    initCharts();
    loadOverview();
    updateCustomerDistribution();
    updateCustomerBehavior();
    updateAssetDistribution();
    updateMarketingEffect();
    updateHighValueCustomers();

    // 设置定时刷新
    setInterval(updateDateTime, 1000);
    setInterval(() => {
        loadOverview();
        updateCustomerDistribution();
        updateCustomerBehavior();
        updateAssetDistribution();
        updateMarketingEffect();
        updateHighValueCustomers();
    }, 5 * 60 * 1000); // 每5分钟刷新一次数据

    // 监听窗口大小改变
    window.addEventListener('resize', resizeCharts);
}

// 页面加载完成后初始化
$(document).ready(init);
